﻿using System;

using System.Net;
using System.Net.Sockets;

using System.Text.RegularExpressions;
using System.Threading;
using System.Windows;

using System.Windows.Threading;

namespace WpfApplication1
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public Socket newclient;
        public bool Connected;
        public Thread mThread;
     
        public delegate void MyInvoke(string str);
        private static DispatcherTimer timersend=new DispatcherTimer();
     

        public MainWindow()
        {
            InitializeComponent();
          
        }
        //点击连接进行数据查询
        private void button_Click(object sender, RoutedEventArgs e)
        {
            //校验端口号以及服务地址
            if (initIP())
            {
                Connect();
             
            }
        }

        private Boolean initIP()
        {
            Regex validipregex = new Regex(@"^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$");
            if (serverIP.Text.Trim()!=null && serverIP.Text.Trim().Length != 0 && serverIP.Text.Trim()!="" && validipregex.IsMatch(serverIP.Text.Trim()))
            {
                return true;
            }
            else
            {
                MessageBox.Show("服务器地址输入有误，请重新输入");
                return false;
            }   
        }

        //初始化listview表格显示数据
        public void initList(string msg)
        {
            listView.Items.Add(msg);
        }
        //创建连接
        public void Connect()
        {
            byte[] data = new byte[1024];

            //获取输入框服务地址和端口号
            String IP =serverIP.Text.Trim();
            int Port = Convert.ToInt32(port.Text.Trim());

            //创建连接套词
            IPEndPoint ie = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 502);
           

            newclient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
          
            //尝试连接，否则抛出异常
            try
            {
        
              
                //进行服务器连接
                newclient.Connect(ie);
         
                connect.IsEnabled = false;

                Connected = true;
             

            }
            catch(SocketException e)
            {
                MessageBox.Show("连接服务器失败" + e.Message);
                return;
            }
           
            ThreadStart myThreadStart = new ThreadStart(ReceiveMsg);
            mThread = new Thread(myThreadStart);
            mThread.Start();
            timersend.Tick += new EventHandler(SendMsg);
            timersend.Interval = new TimeSpan(0, 0, 0, 1);
            timersend.Start();
            //     timersend.IsEnabled = true;

        }
        private void timersend_Tick()
        {
            ////设置时间间隔
            //   TimeSpan isecond = new TimeSpan(1000);
            //  timersend.Interval = isecond;
            //  byte[] data = new byte[] { 0x00, 0x0f, 0x00, 0x00, 0x06, 0x01, 0x04, 0x00, 0x00, 0x00, 0x01 };
            //  newclient.Send(data);

         //   timersend.Tick += new EventHandler(SendMsg);
         //   timersend.Interval = new TimeSpan(0, 0, 1);
        

        }

        private void SendMsg(object sender, EventArgs e)
        {
            byte[] data = new byte[] { 0x00, 0x0f, 0x00, 0x00, 0x00, 0x06, 0x01, 0x03, 0x00, 0x00, 0x00, 0x0A };
            newclient.Send(data);
        }

        //接收参数
        public void ReceiveMsg()
        {
            while (true)
            {
                byte[] data = new byte[1024];//定义数据接收数组  
                newclient.Receive(data);//接收数据到data数组  
               int length = data[5];//读取数据长度  
                Byte[] datashow = new byte[length + 6];//定义所要显示的接收的数据的长度  
                for (int i = 0; i <= length + 5; i++)//将要显示的数据存放到数组datashow中  
                    datashow[i] = data[i];
               string stringdata = BitConverter.ToString(datashow);//把数组转换成16进制字符串  
                MessageBox.Show(stringdata);
                if (data[7] == 0x01)
                {
                    listView.Items.Add(stringdata + "\r\n");
                 
                    
                         };
          
           

            }
        }
      
    }
}
